<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>规则设置</title>
    <link rel="stylesheet" href="../utils/bootstrap-5.3.3-dist/css/bootstrap.min.css">
    <script src="../utils/bootstrap-5.3.3-dist/js/bootstrap.min.js"></script>
    <link rel="stylesheet" href="../utils/flatpickr/flatpickr.min.css">
    <script src="../utils/flatpickr/flatpickr.min.js"></script>
    <link rel="stylesheet" href="../utils/icon/iconfont.css">
    <link rel="stylesheet" href="../css/shared.css">
    <style>
        /*中部布局*/
        .central-layout {
            display: grid;
            grid-template-rows: 40px 550px;
            width: 100%;
            margin: 0 auto;
        }

        /*中部底部布局*/
        .central-bottom-layout {
            display: grid;
            grid-template-rows: 50px 450px 50px;
            width: 80vw;
            margin: 0 auto;
        }

        /*中部底部头部布局*/
        .c-b-head {
            display: flex;
            flex-direction: row;
            align-items: center;
            gap: 10px;
            padding: 5px;
            justify-content: space-evenly;;
        }

        /*路线设置布局*/
        .route-grid {
            display: grid;
            grid-template-rows: 50px 20px 50px;
            background-color: #c6c7c8;
            height: 120px;
            width: 700px;
        }

        .route-arrow {
            display: flex;
            flex-direction: row;
            align-items: center;
            justify-content: center;
        }

        .route-arrow-margin {
            margin: 0 15px;
        }

        .route-button {
            display: block;
            margin: auto;
        }

        .route-option {
            display: grid;
            grid-template-columns: repeat(auto-fill, 50px);
            margin: auto 0;
        }

        .move-div {
            position: relative;
            z-index: 0;
        }

        /*规则设置弹窗布局*/
        /*两个div进行flex布局*/
        .two-div-flex {
            display: flex;
        }

        .algorithm-example {
            display: flex;
            padding: 5px;
            align-items: center;
            justify-content: space-between;
        }

    </style>
</head>
<body>
<div class="body-grid">
    <!--头部-->
    <div class="header-grid">
        <!--    返回按钮-->
        <div>
            <!--            <button class="btn btn-secondary iconfont go-back-button" onclick="window.location.href='card-issuance.html';">-->
            <!--                &#xe623;-->
            <!--            </button>-->
        </div>
        <!--    标题-->
        <div class="page-title" id="page-title">
            <script>
                document.getElementById("page-title").innerText=window.sessionStorage.getItem("competitionName")
                +"--规则设置"
            </script>
        </div>
        <div></div>
    </div>
    <!--中部-->
    <div class="central-layout">
        <div>
            <!--        顶部导航-->
            <div class="btn-group">
                <button type="button" class="btn btn-primary" onclick="window.location.href='batch.html'">批次管理
                </button>
                <button type="button" class="btn btn-primary" onclick="window.location.href='rule.html'">规则设置
                </button>
                <button type="button" class="btn btn-primary" onclick="window.location.href='start-game.html'">
                    开始比赛
                </button>
                <button type="button" class="btn btn-primary" onclick="window.location.href='calculate-score.html'">
                    成绩计算
                </button>
                <button type="button" class="btn btn-primary" onclick="window.location.href='replace-card.html'">补卡
                </button>
            </div>
        </div>

        <div class="central-bottom-layout">
            <div class="c-b-head">
                <label>
                    比赛项目：
                    <select id="project-search" onchange="showSearch()">
                        <option value="">全部</option>
                    </select>
                </label>
                <button type="button" class="btn btn-primary" onclick="downloadRules()">
                    导出比赛规则表
                </button>
            </div>
            <div class="table-responsive">
                <table id="rule-table" class="table table-sm table-bordered text-center">
                    <thead>
                    <tr>
                        <th>比赛项目</th>
                        <th>组别</th>
                        <th>路线</th>
                        <th>限时</th>
                        <th>商定算法</th>
                        <th>操作</th>
                    </tr>
                    </thead>
                    <tbody id="rule-tbody" class="table-group-divider">

                    </tbody>
                </table>
            </div>
            <div>
                <!--    分页组件-->
                <ul class="pagination page-ul-flex" id="pagination">
                </ul>
            </div>
        </div>

    </div>
    <!--尾部-->
    <div class="footer-grid">
        <!--网格留空-->
        <div></div>
        <!--进度条-->
        <div id="progress-bar" class="progress-bar-flex">
            <div class="progress-bar-grid">
                <button type="button" class="btn btn-success progress-bar-button" disabled></button>
                <div class="progress-bar-text">新增赛事</div>
                <i class="iconfont progress-bar-arrow">&#xe604;</i>
            </div>
            <div class="progress-bar-grid">
                <button type="button" class="btn btn-success progress-bar-button" disabled></button>
                <div class="progress-bar-text">新增项目</div>
                <i class="iconfont progress-bar-arrow">&#xe604;</i>
            </div>
            <div class="progress-bar-grid">
                <button type="button" class="btn btn-success progress-bar-button" disabled></button>
                <div class="progress-bar-text">设置组别</div>
                <i class="iconfont progress-bar-arrow">&#xe604;</i>
            </div>
            <div class="progress-bar-grid">
                <button type="button" class="btn btn-success progress-bar-button" disabled></button>
                <div class="progress-bar-text">导入选手</div>
                <i class="iconfont progress-bar-arrow">&#xe604;</i>
            </div>
            <div class="progress-bar-grid">
                <button type="button" class="btn btn-success progress-bar-button" disabled></button>
                <div class="progress-bar-text">下发号码</div>
                <i class="iconfont progress-bar-arrow">&#xe604;</i>
            </div>
            <div class="progress-bar-grid">
                <button type="button" class="btn btn-success progress-bar-button" disabled></button>
                <div class="progress-bar-text">制卡</div>
                <i class="iconfont progress-bar-arrow">&#xe604;</i>
            </div>
            <div class="progress-bar-grid">
                <button type="button" class="btn btn-success progress-bar-button" disabled></button>
                <div class="progress-bar-text">签到</div>
                <i class="iconfont progress-bar-arrow">&#xe604;</i>
            </div>
            <div class="progress-bar-grid">
                <button type="button" class="btn btn-success progress-bar-button" disabled></button>
                <div class="progress-bar-text">批次管理</div>
                <i class="iconfont progress-bar-arrow">&#xe604;</i>
            </div>
            <div class="progress-bar-grid">
                <button type="button" class="btn btn-success progress-bar-button" disabled></button>
                <div class="progress-bar-text">规则设置</div>
                <i class="iconfont progress-bar-arrow">&#xe604;</i>
            </div>
            <div class="progress-bar-grid">
                <button type="button" class="btn btn-success progress-bar-button" disabled></button>
                <div class="progress-bar-text">开始比赛</div>
                <i class="iconfont progress-bar-arrow">&#xe604;</i>
            </div>
            <div class="progress-bar-grid">
                <button type="button" class="btn btn-success progress-bar-button" disabled></button>
                <div class="progress-bar-text">成绩计算</div>
                <i class="iconfont progress-bar-arrow" style="visibility: hidden;">&#xe604;</i>
            </div>
        </div>
        <!--   占位不能删-->
        <div>
        </div>
    </div>
</div>
<!--规则设置弹窗-->
<div id="edit-rule-dialog" class="my-dialog my-dialog-larger" style="display: none">
    <div class="my-dialog-header">
        <!--                    标题占位-->
        <span>规则设置</span>
        <button type="button" class="btn-close close-icon"
                onclick="closeEditRuleDialog()"></button>
    </div>
    <div class="my-dialog-body">
        <div class="two-div-flex">
            <div class="input-layout">
                <div class="label-area">
                    <label for="project-name">项目：</label>
                </div>
                <div class="input-area">
                    <input type="text" id="project-name" readonly>
                </div>
                <div class="err-area">
                    <small style="color: red;"></small>
                </div>
            </div>
            <div class="input-layout">
                <div class="label-area">
                    <label for="group-name">组别：</label>
                </div>
                <div class="input-area">
                    <input type="text" id="group-name" readonly>
                </div>
                <div class="err-area">
                    <small style="color: red;"></small>
                </div>
            </div>
        </div>
        <div class="two-div-flex">
            <div class="input-layout">
                <div class="label-area">
                    <label for="limit-time">限时<span style="color:red;">*</span>：</label>
                </div>
                <div class="input-area">
                    <input id="limit-time" placeholder="时:分:秒">
                </div>
                <div class="err-area">
                    <small style="color: red;"></small>
                </div>
            </div>
            <div class="input-layout">
                <div class="label-area">
                    <label for="edit-algorithm">算法设置<span style="color:red;">*</span>：</label>
                </div>
                <div class="input-area">
                    <input type="text" id="edit-algorithm" readonly>
                    <button class="btn btn-primary btn-sm" id="edit-algorithm-btn" onclick="openEditAlgorithmDialog()">设置算法</button>
                </div>
                <div class="err-area">
                    <small style="color: red;"></small>
                </div>
            </div>
        </div>
        <div class="input-layout">
            <div class="label-area">
                路线设置<span style="color:red;">*</span>：
            </div>
            <div class="input-area">
                <div class="route-grid">
                    <div class="route-option" id="selected-route">
                    </div>
                    <div class="route-arrow">
                        <div class="iconfont route-arrow-margin">&#xe60b;</div>
                    </div>
                    <div class="route-option" id="unselected-route">
                    </div>
                </div>
            </div>
            <div class="err-area">
                <small style="color: red;" id="route-err"></small>
            </div>
        </div>

    </div>
    <div class="my-dialog-footer">
        <button type="button" class="btn btn-secondary btn-sm my-dialog-ft-btn"
                onclick="closeEditRuleDialog()">取消
        </button>
        <button type="button" class="btn btn-primary btn-sm my-dialog-ft-btn"
                onclick="submitEditRuleDialog()">确认
        </button>
    </div>
</div>
<!--算法设置弹窗-->
<div id="edit-algorithm-dialog" class="my-dialog" style="display: none">
    <div class="my-dialog-header">
        <!--                    标题占位-->
        <span>算法设置</span>
        <button type="button" class="btn-close close-icon"
                onclick="closeEditAlgorithmDialog()"></button>
    </div>
    <div class="my-dialog-body">
        <!--        <div class="algorithm-example">-->
        <!--            <label><input type="radio" name="algorithm-type" value="1">算法1</label>-->
        <!--            <button class="btn btn-primary btn-sm">例子</button>-->
        <!--        </div>-->
    </div>
    <div class="my-dialog-footer">
        <button type="button" class="btn btn-secondary btn-sm my-dialog-ft-btn"
                onclick="closeEditAlgorithmDialog()">取消
        </button>
        <button type="button" class="btn btn-primary btn-sm my-dialog-ft-btn"
                onclick="submitEditAlgorithmDialog()">确认
        </button>
    </div>
</div>
<!--算法例子弹窗-->
<div id="algorithm-example-dialog" class="my-dialog" style="display: none">
    <div class="my-dialog-header">
        <!--                    标题占位-->
        <span></span>
        <button type="button" class="btn-close close-icon"
                onclick="closeDialogWithBackgroundId('algorithm-example-dialog','a-e-d-bg')"></button>
    </div>
    <div class="my-dialog-body">
        <p>

        </p>
    </div>
    <div class="my-dialog-footer">
    </div>
</div>
<script src="../js/pages.js"></script>
<script src="../api/urls.js"></script>
<script src="../js/dialog.js"></script>
<script src="../js/progress.js"></script>
<script>
    updateProgress("progress-bar", RULE_PROGRESS);
    //页码
    let pageNum = 1;
    //一页多少条
    let pageSize = 20;
    //总条数
    let total;
    //总页数
    let pages;
    //请求记录
    let records;
    //更新id
    let updateId;
    //项目id
    let projectId = null;
    //已选路线
    let selectedRoute = [];
    //未选路线
    let unSelectedRoute = ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10', 'MO', 'S'];



    /**
     *创建已选路线
     */
    function createSelectedRoute(routes) {
        let selectedRouteElement = document.getElementById("selected-route");
        selectedRouteElement.innerHTML = '';
        for (let route of routes) {
            let divElement = document.createElement("div");
            divElement.classList.add("move-div")
            let buttonElement = document.createElement("button");
            buttonElement.classList.add("btn", "btn-sm", "btn-primary", "route-button");
            buttonElement.textContent = route;
            buttonElement.addEventListener("contextmenu", (event) => {
                event.preventDefault();
            });
            buttonElement.addEventListener("mousedown", (ev) => {

                if (ev.button === 0) { //左键
                    let computedStyle = window.getComputedStyle(buttonElement.parentElement);
                    let clx = ev.clientX - parseInt(computedStyle.left.slice(0, -2), 10);
                    let sl = ev.clientX - buttonElement.parentElement.offsetLeft;
                    const moveHandler = (evt) => {
                        let left = evt.clientX - sl;
                        let right = left + buttonElement.parentElement.offsetWidth;
                        let lastRight;
                        let lastElementChild = buttonElement.parentElement.parentElement.lastElementChild;
                        if (lastElementChild) {
                            lastRight = lastElementChild.offsetWidth + lastElementChild.offsetLeft;
                        } else {
                            lastRight = buttonElement.parentElement.parentElement.offsetWidth;
                        }
                        if (left >= 0 && right <= lastRight) {
                            buttonElement.parentElement.style.zIndex = "1";
                            buttonElement.parentElement.style.left = evt.clientX - clx + "px";
                        }
                    };
                    document.addEventListener("mousemove", moveHandler);
                    const upHandler = () => {
                        document.removeEventListener("mousemove", moveHandler);
                        let pLeft = buttonElement.parentElement.offsetLeft;
                        for (let child of buttonElement.parentElement.parentElement.children) {
                            if (child.offsetLeft > pLeft && child !== buttonElement.parentElement.parentElement.lastElementChild) {
                                selectedRoute.splice(selectedRoute.indexOf(buttonElement.textContent), 1);
                                selectedRoute.splice(selectedRoute.indexOf(child.firstElementChild.textContent), 0, buttonElement.textContent);
                                break;
                            } else if (child === buttonElement.parentElement.parentElement.lastElementChild) {
                                selectedRoute.splice(selectedRoute.indexOf(buttonElement.textContent), 1);
                                selectedRoute.push(buttonElement.textContent);
                            }
                        }
                        createSelectedRoute(selectedRoute);
                        document.removeEventListener("mouseup", upHandler);
                    };
                    document.addEventListener("mouseup", upHandler);
                } else if (ev.button === 2) { //右键
                    unSelectedRoute.push(buttonElement.textContent);
                    selectedRoute.splice(selectedRoute.indexOf(buttonElement.textContent), 1);
                    unSelectedRoute.sort();
                    createSelectedRoute(selectedRoute);
                    createUnSelectedRoute(unSelectedRoute);
                }
            });
            divElement.append(buttonElement);
            selectedRouteElement.append(divElement);
        }
        let divElement = document.createElement("div");
        let buttonElement = document.createElement("button");
        buttonElement.classList.add("btn", "btn-sm", "btn-info", "route-button");
        buttonElement.textContent = "终点";
        buttonElement.addEventListener("contextmenu", (event) => {
            event.preventDefault();
        });
        divElement.append(buttonElement);
        selectedRouteElement.append(divElement);
        let divElement1 = document.createElement("div");
        let buttonElement1 = document.createElement("button");
        buttonElement1.classList.add("btn", "btn-sm", "btn-info", "route-button");
        buttonElement1.textContent = "起点";
        buttonElement1.addEventListener("contextmenu", (event) => {
            event.preventDefault();
        });
        divElement1.append(buttonElement1);
        selectedRouteElement.prepend(divElement1);
    }

    /**
     *创建未选路线
     */
    function createUnSelectedRoute(routes) {
        let unselectedRouteElement = document.getElementById("unselected-route");
        unselectedRouteElement.innerHTML = '';
        for (let route of routes) {
            let divElement = document.createElement("div");
            let buttonElement = document.createElement("button");
            buttonElement.classList.add("btn", "btn-sm", "btn-primary", "route-button");
            buttonElement.textContent = route;
            buttonElement.addEventListener("click", () => {
                selectedRoute.push(buttonElement.textContent);
                unSelectedRoute.splice(unSelectedRoute.indexOf(buttonElement.textContent), 1);
                createSelectedRoute(selectedRoute);
                createUnSelectedRoute(unSelectedRoute);
            });
            divElement.append(buttonElement);
            unselectedRouteElement.append(divElement);
        }
    }


    /**
     * 点击搜索
     */
    async function showSearch() {
        pageNum = 1;
        await showPage();
    }

    /**
     *获取项目下拉菜单
     */
    async function getProjectMenu() {

        let url = new URL(RULE_URL + "/getProjectMenu");
        url.searchParams.set("competitionId", window.sessionStorage.getItem("competitionId"));
        await fetch(url).then(r => {
            return r.json()
        }).then(result => {
            let projectSearch = document.getElementById("project-search");
            for (const projectMenu of result) {
                let option = document.createElement("option");
                option.value = projectMenu.projectId;
                option.textContent = projectMenu.projectName;
                projectSearch.append(option);
            }
        });
    }

    /**
     * 校验规则设置数据
     */
    function verifyData() {
        let flag = true;
        let limitTime = document.getElementById("limit-time");
        if (!limitTime.value) {
            flag = false;
            limitTime.parentElement.parentElement.lastElementChild.firstElementChild.textContent = "限时不能为空！";
        }
        let algorithmName = document.getElementById("edit-algorithm");
        if (!algorithmName.value) {
            flag = false;
            algorithmName.parentElement.parentElement.lastElementChild.firstElementChild.textContent = "算法不能为空！";
        }
        if (!(selectedRoute && selectedRoute.length !== 0)) {
            flag = false;
            document.getElementById("route-err").textContent = "路线不能为空！"
        }else {
          //  if(selectedRoute[selectedRoute.length-1]!=="MO"){
           //     flag = false;
           //     document.getElementById("route-err").textContent = "路线最后一个站必须是MO！"
           // }
            let projectName = document.getElementById("project-name");
           // if(projectName.value.split("-")[2]==="接力"&&selectedRoute.length!==10){
            //    flag = false;
           //     document.getElementById("route-err").textContent = "接力赛站数必须是9个站+MO站！"
           // }
            if(projectName.value.split("-")[0]==="快速"&&!selectedRoute.includes("S")){
                flag = false;
                document.getElementById("route-err").textContent = "快速赛必须包含S站！"
            }

        }
        return flag;
    }

    /**
     * 提交规则设置
     */
    async function submitEditRuleDialog() {
        let smalls = document.querySelectorAll("#edit-rule-dialog small");
        for (let small of smalls) {
            small.textContent = null;
        }
        if (!verifyData()) {
            return;
        }
        //提交修改数据
        let requestBody={};
        requestBody.ruleId=updateId;
        requestBody.algorithmId=document.getElementById("edit-algorithm").dataset.algorithmId;
        selectedRoute.unshift("起点");
        selectedRoute.push("终点");
        requestBody.route=selectedRoute;
        requestBody.limitTime=document.getElementById("limit-time").value;
        await fetch(RULE_URL+UPDATE_URL,{
            method: "POST",
            headers: new Headers({"Content-Type": "application/json"}),
            body: JSON.stringify(requestBody)
        });
        closeEditRuleDialog();
        await showPage();
    }

    /**
     * 提交编辑算法弹窗
     */
    function submitEditAlgorithmDialog() {
        let algorithmType = document.querySelector("#edit-algorithm-dialog input[name='algorithm-type']:checked");
        if(algorithmType){
            if(algorithmType.parentElement.textContent.startsWith("(商定)")){
                document.getElementById("edit-algorithm").value=algorithmType.parentElement.textContent.substring(4);
            }else {
                document.getElementById("edit-algorithm").value=algorithmType.parentElement.textContent;
            }

        }
        let algorithmName = document.getElementById("edit-algorithm");
        algorithmName.dataset.algorithmId=algorithmType.value;
        closeEditAlgorithmDialog();
    }

    /**
     * 关闭规则设置弹窗
     */
    function closeEditRuleDialog() {
        let smalls = document.querySelectorAll("#edit-rule-dialog small");
        for (let small of smalls) {
            small.textContent = null;
        }
        selectedRoute = [];
        unSelectedRoute = ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10', 'MO', 'S'];
        let projectName = document.getElementById("project-name");
        projectName.value = null;
        let groupName = document.getElementById("group-name");
        groupName.value = null;
        let limitTime = document.getElementById("limit-time");
        limitTime.value = null;
        //使用flatpickr自定义时间选择器
        window.flatpickr("#limit-time", {
            enableTime: true, // 启用时间选择
            noCalendar: true, // 不显示日期选择器，只显示时间选择器
            enableSeconds: true, // 启用秒的选择
            time_24hr: true, // 使用24小时制
            dateFormat: "H:i:S", // 设置日期格式为仅包含时间（小时:分钟:秒）
        });
        let algorithmName = document.getElementById("edit-algorithm");
        algorithmName.value = null;
        delete algorithmName.dataset.algorithmId;
        closeDialog("edit-rule-dialog");
    }

    /**
     * 关闭算法设置弹窗
     */
    function closeEditAlgorithmDialog() {
        let element = document.querySelector("#edit-algorithm-dialog .my-dialog-body");
        element.innerHTML = "";
        closeDialogWithBackgroundId("edit-algorithm-dialog", "edit-algorithm-bg");
    }

    /**
     * 打开算法设置弹窗
     */
    async function openEditAlgorithmDialog() {
        //请求算法数据
        let url = new URL(ALGORITHM_URL + "/getAlgorithmMenu");
        url.searchParams.set("ruleId", updateId);
        await fetch(url).then(resp => resp.json()).then(result => {
            let dialogBody = document.querySelector("#edit-algorithm-dialog .my-dialog-body");
            for (const resultElement of result) {
                let div = document.createElement("div");
                div.classList.add("algorithm-example");
                let label = document.createElement("label");
                let input = document.createElement("input");
                input.type = "radio";
                input.name = "algorithm-type";
                input.value = resultElement.algorithmId;
                let algorithmId = document.getElementById("edit-algorithm").dataset.algorithmId;
                if(algorithmId&&Number(algorithmId)===resultElement.algorithmId){
                    input.checked=true;
                }
                label.append(input,resultElement.algorithmName);
                let button = document.createElement("button");
                button.classList.add("btn", "btn-primary", "btn-sm");
                button.textContent = "例子";
                button.addEventListener("click", () => {
                    let p = document.querySelector("#algorithm-example-dialog .my-dialog-body p");
                    p.innerHTML = resultElement.algorithmDescription;
                    openDialogWithBackgroundIdAndZIndex("algorithm-example-dialog", "a-e-d-bg", 13);
                });
                div.append(label, button);
                dialogBody.append(div);
            }
        })
        openDialogWithBackgroundIdAndZIndex("edit-algorithm-dialog", "edit-algorithm-bg", 11);
    }

    /**
     * 打开规则设置弹窗
     */
    async function openEditRuleDialog(record) {
        selectedRoute = [];
        let projectType = record.projectName.split("-")[0];
        if (projectType === "快速") {
            unSelectedRoute = ['1', '2', '3', '4', '5', 'F1', 'F2', 'F3', 'F4', 'F5', 'MO', 'S'];
        } else {
            unSelectedRoute = ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10', 'MO'];
        }
        if (record.route) {
            let routeStrs = record.route.split("-");
            if(routeStrs.indexOf("起点")!==-1){
                routeStrs.splice(routeStrs.indexOf("起点"),1);
            }
            if(routeStrs.indexOf("终点")!==-1){
                routeStrs.splice(routeStrs.indexOf("终点"),1);
            }
            selectedRoute = routeStrs;
            unSelectedRoute = unSelectedRoute.filter(item => !routeStrs.includes(item));
        }
        let projectName = document.getElementById("project-name");
        projectName.value = record.projectName;
        let groupName = document.getElementById("group-name");
        groupName.value = record.groupName;
        let limitTime = document.getElementById("limit-time");
        limitTime.value = record.limitTime;
        //使用flatpickr自定义时间选择器
        window.flatpickr("#limit-time", {
            enableTime: true, // 启用时间选择
            noCalendar: true, // 不显示日期选择器，只显示时间选择器
            enableSeconds: true, // 启用秒的选择
            time_24hr: true, // 使用24小时制
            dateFormat: "H:i:S", // 设置日期格式为仅包含时间（小时:分钟:秒）
        });
        let algorithmName = document.getElementById("edit-algorithm");
        if(record.algorithmId){
            algorithmName.dataset.algorithmId=record.algorithmId;
        }
        algorithmName.value = record.algorithmTypeName;
        createSelectedRoute(selectedRoute);
        createUnSelectedRoute(unSelectedRoute);
        openDialog("edit-rule-dialog");
    }

    /**
     * 渲染表格
     */
    function drawRuleTable(records) {
        let tableBody = document.getElementById("rule-tbody");
        tableBody.innerHTML = "";
        for (let record of records) {
            let trElement = document.createElement("tr");
            let tdElement1 = document.createElement("td");
            tdElement1.textContent = record.projectName;
            let tdElement2 = document.createElement("td");
            tdElement2.textContent = record.groupName;
            let tdElement3 = document.createElement("td");
            tdElement3.textContent = record.route;
            let tdElement4 = document.createElement("td");
            tdElement4.textContent = record.limitTime;
            let tdElement5 = document.createElement("td");
            tdElement5.textContent = record.algorithmTypeName;
            let tdElement11 = document.createElement("td");
            let buttonElement1 = document.createElement("button");
            buttonElement1.classList.add("btn", "btn-primary", "btn-sm", "iconfont");
            buttonElement1.textContent = "\u{e6f7}规则设置";
            if(new Date(record.projectTime).getTime() > new Date().getTime()){
                

                buttonElement1.addEventListener("click", () => {
                    updateId = record.ruleId;
                    openEditRuleDialog(record);
                });
                buttonElement1.disabled=false
            }else{
                buttonElement1.disabled=true
            }
            
            tdElement11.append(buttonElement1);
            trElement.append(tdElement1, tdElement2, tdElement3, tdElement4, tdElement5, tdElement11);
            tableBody.append(trElement);
        }
    }
    /**
     * 下载规则表
     */
    async function downloadRules() {
        let url1 = new URL(RULE_URL + "/download");
        url1.searchParams.set("competitionId", window.sessionStorage.getItem("competitionId"));
        await fetch(url1).then(resp => {
            return resp.blob();
        }).then(blob => {
            // 创建一个指向 Blob 的 URL
            const url = window.URL.createObjectURL(blob);

            // 创建 <a> 元素
            const a = document.createElement('a');
            a.style.display = 'none';
            a.href = url;
            a.download = '比赛规则表.xlsx'; // 设置下载的文件名

            // 添加 <a> 到文档中，并触发点击事件
            document.body.appendChild(a);
            a.click();

            // 清理资源
            window.URL.revokeObjectURL(url);
            document.body.removeChild(a);
        });
    }

    //实现分页的方法
    async function getPage(pageNum, pageSize) {
        let searchInput = document.getElementById("project-search");
        projectId = searchInput.value;
        let url = new URL(RULE_URL + "/searchAll");
        url.searchParams.set("pageNum", pageNum);
        url.searchParams.set("pageSize", pageSize);
        url.searchParams.set("competitionId", window.sessionStorage.getItem("competitionId"));
        if (projectId) {
            url.searchParams.set("projectId", projectId);
        }
        await fetch(url).then(response => {
            if (response.ok && response.headers.get("Content-Type") === "application/json") {
                return response.json();
            } else {
                throw new Error(`未知相应状态 ${response.status}或Content-Type：${response.headers.get("Content-Type")}`);
            }
        }).then(pageInfo => {
            pages = pageInfo.pages;
            total = pageInfo.total;
            records = pageInfo.records;
            drawRuleTable(records);
        }).catch(error => {
            console.log("分页错误：", error);
        });
    }

    //上一页
    async function prePage() {
        pageNum = pageNum - 1;
        await getPage(pageNum, pageSize);
        createpage(pageNum, pageSize, total, pages);
    }

    //下一页
    async function nextPage() {
        pageNum = pageNum + 1;
        await getPage(pageNum, pageSize);
        createpage(pageNum, pageSize, total, pages)
    }

    //点击切换
    async function handlePage(page) {
        if (page !== pageNum) {
            pageNum = page
            await getPage(pageNum, pageSize);
            createpage(pageNum, pageSize, total, pages);
        }

    }

    /**
     * 改变每页条数
     */
    async function changePageSize(value) {
        pageSize = Number(value);
        await getPage(pageNum, pageSize);
        createpage(pageNum, pageSize, total, pages);
    }

    // 创建分页组件
    async function showPage() {
        await getPage(pageNum, pageSize);
        createpage(pageNum, pageSize, total, pages);
    }

    if (window.sessionStorage.getItem("competitionId")) {
        (async () => {
            await getProjectMenu();
            await showPage();
        })();
    }
</script>
</body>
</html>